import time
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options as Option_chrome
from selenium import webdriver


def get_chrome_driver():
    # 设置为无头浏览器
    opt = Option_chrome()
    opt.add_argument("--headless")
    opt.add_argument('window-size=1920x1080')
    opt.add_argument('--start-maximized')
    opt.add_argument("--disable-gpu")
    opt.add_argument("--no-sandbox")
    opt.add_argument("-–single-process")
    opt.add_argument('ignore-certificate-errors')
    # prefs = {"profile.managed_default_content_settings.images": 2, "profile.managed_default_content_settings.javascript": 2}          # 禁止图片加载、js执行
    prefs = {"profile.managed_default_content_settings.images": 2}          # 禁止图片加载、js执行
    opt.add_experimental_option("prefs", prefs)

    # 浏览器请求头
    chromeAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36'
    opt.add_argument("--user-agent=" + chromeAgent)
    # 设置为开发者模式
    opt.add_experimental_option('excludeSwitches', ['enable-automation'])
    # opt.add_experimental_option('useAutomationExtension', False)
    # 禁用启用Blink运行时的功能
    opt.add_argument("--disable-blink-features=AutomationControlled")
    driver = webdriver.Chrome(options=opt)
    # 再次覆盖window.navigator.webdriver的值
    driver.execute_cdp_cmd(
        "Page.addScriptToEvaluateOnNewDocument",
        {"source": """ Object.defineProperty(navigator, 'webdriver', { get: () => undefined }) """}
    )
    return driver


def selenium_get(href):
    driver = get_chrome_driver()
    driver.set_page_load_timeout(20)
    driver.implicitly_wait(15)
    try:
        driver.get(href)
    except:  # 报错后就强制停止加载 # 这里是js控制
        driver.execute_script('window.stop()')
    time.sleep(2)
    try:
        html_text = driver.page_source
    except:
        return None, None
    current_url = driver.current_url
    driver.close()
    return html_text, current_url

